package com.revenco.bi.service.impl;

import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.nutz.json.Json;
import org.nutz.lang.Lang;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.revenco.bi.dao.ChartSqlDao;
import com.revenco.bi.dao.ViewEditChartDao;
import com.revenco.bi.model.TnChartBaseinfo;
import com.revenco.bi.model.TnChartDataitems;
import com.revenco.bi.model.TnChartParams;
import com.revenco.bi.model.TnColumnInfo;
import com.revenco.bi.model.TnTableColumnRelation;
import com.revenco.bi.model.TnTableInfo;
import com.revenco.bi.model.userbean.AnychartDataBean;
import com.revenco.bi.model.userbean.CFieldsBean;
import com.revenco.bi.model.userbean.CQueryBean;
import com.revenco.bi.model.userbean.CYDetailBean;
import com.revenco.bi.model.userbean.MTRelationsBean;
import com.revenco.bi.model.userbean.MultiTableRelationBean;
import com.revenco.bi.model.userbean.OilGaugeBean;
import com.revenco.bi.model.userbean.XFieldsBean;
import com.revenco.bi.model.userbean.YFieldsBean;
import com.revenco.bi.model.userbean.YQueryBean;
import com.revenco.bi.service.ChartService;
import com.revenco.bi.service.ChartSqlPieceService;
import com.revenco.bi.service.TnColumnInfoService;
import com.revenco.bi.service.TnTableInfoService;
import com.revenco.bi.service.ViewEditChartService;
import com.revenco.bi.util.ColorUtils;
import com.revenco.bi.util.JsonBinder;
import com.revenco.bi.util.SqlTemplate;
import com.revenco.bi.util.XmlUtils;

/**
 * 预览编辑图表
 * 
 * @author zhaozz
 * 
 */
@Service
public class ViewEditChartServiceImpl implements ViewEditChartService {
	@Autowired
	ViewEditChartDao vecDao;
	@Autowired
	ChartSqlDao chartSqlDao;
	@Autowired
	private ChartService chartService;
	@Autowired
	private ChartSqlPieceService chartSqlPieceService;
	@Autowired
	private TnColumnInfoService tInfoService;
	
	@Autowired
	private TnTableInfoService tableInfoService;
	

	JsonBinder binder = new JsonBinder();

	protected final Logger log = LoggerFactory.getLogger(getClass());

	/**
	 * 获取图标基本信息表
	 * 
	 * @param chartId
	 * @return
	 */
	public String getChartinfo(Model model, HttpServletResponse response,
			String chartId, String params) {
		String viewUrl = "";
		try {
			TnChartBaseinfo tcb = vecDao.getChartInfo(chartId);
			List<TnChartDataitems> tcDataList = vecDao.getChartDatas(chartId);
			List<TnChartParams> tcParamsList = vecDao.getChartParams(chartId);
			viewUrl = viewAndEditChart(model, response, tcb, tcDataList,
					tcParamsList, params);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return viewUrl;
	}

	@ResponseStatus(HttpStatus.OK)
	public String viewAndEditChart(Model model, HttpServletResponse response,
			TnChartBaseinfo tChartInfo, List<TnChartDataitems> tcDataList,
			List<TnChartParams> tcParamsList, String params)
			throws UnsupportedEncodingException {

		String chartType = tChartInfo.getChartType(); // 图表类型

		int tctcSize = tcDataList.size();
		List<String> yFiledNameList = new ArrayList<String>();
		for (int i = 0; i < tctcSize; i++) {
			yFiledNameList.add(tcDataList.get(i).getyFieldCd());// 来源数据库TnChartDataitems表Y_FIELD_NAME
		}

		// 创建SQL
		String tempSql = null;
		tempSql = this.createSql(params, tChartInfo, tcParamsList);

		// 获取xml图表data数据
		StringBuilder data = new StringBuilder();
		if ("circularGauge".equals(chartType)) {
			data = this.getCircleGauge(tempSql, yFiledNameList, tcDataList);
		} else {
			data = this.getFourTypeData(tempSql, yFiledNameList, chartType,
					tcDataList);
		}

		model = this.getModelInfo(model, tChartInfo, data, tcDataList,
				tcParamsList);

		return this.getUrl(chartType);
	}

	/**
	 * 封装显示图表所需属性
	 * 
	 * @param model
	 * @param tChartInfo
	 * @param data
	 * @param maxCount
	 * @param minCount
	 * @param num
	 * @param legend_unit
	 * @return
	 */
	public Model getModelInfo(Model model, TnChartBaseinfo tChartInfo,
			StringBuilder data, List<TnChartDataitems> tcDataList,
			List<TnChartParams> tcParamsList) {

		String strJson = tChartInfo.getChartConfigJson(); // 图形属性
		String xAsixValue = tChartInfo.getxFieldName();// x-轴字段显示值
		String chartType = tChartInfo.getChartType(); // 图表类型
		@SuppressWarnings("rawtypes")
		Map mapTemp = new HashMap();
		mapTemp = Json.fromJson(HashMap.class, Lang.inr(strJson));

		String maxCount = "";
		String minCount = "";
		String legend_unit = tcDataList.get(0).getDataUnit(); // 获取图例单位
		double num = 0;
		DecimalFormat df = new DecimalFormat("0");// 格式化小数
		if ("circularGauge".equals(chartType)) {
			String tables = tChartInfo.getExt3();
			String columnStr = "";
			// 获取y轴字段来源于表名称
			String eds = tcDataList.get(0).getyFieldTableName();
			// 循环获取y轴字段字符串
			Iterator<TnChartDataitems> it = tcDataList.iterator();
			TnChartDataitems tDataitems = new TnChartDataitems();
			SqlTemplate sqlTemplate = new SqlTemplate();
			while (it.hasNext()) {
				tDataitems = it.next();
				if (StringUtils.isEmpty(tDataitems.getyValueOpType())) {
					columnStr += sqlTemplate.splitString(tDataitems.getExt1());
				} else {
					columnStr += tDataitems.getyValueOpType() + "("
							+ tDataitems.getyFieldCd() + ")";
				}
				
				if (it.hasNext()) {
					columnStr += ", ";
				}
			}
			@SuppressWarnings("unchecked")
			List<TnTableColumnRelation> tnList = (List<TnTableColumnRelation>) vecDao.getChartDetail(TnTableColumnRelation.class,
					tChartInfo.getChartId());
			String columnSQL = this.getOilGaugeBeanInfoOfSql2(columnStr, eds, tables, tnList);
			OilGaugeBean oBean2 = chartService.getOilGaugeBeanInfo(columnSQL);
			num = (Double.valueOf(oBean2.getMaxCount() == null ? "0" : oBean2.getMaxCount()) - Double
					.valueOf(oBean2.getMinCount() == null ? "0" : oBean2.getMinCount())) / 10;
			maxCount = df.format(Double.valueOf(oBean2.getMaxCount() == null ? "0" : oBean2.getMaxCount())); // 油量表最大刻度
			minCount = df.format(Double.valueOf(oBean2.getMinCount() == null ? "0" : oBean2.getMinCount()) - num); // 油量表最小刻度
		}

		// 以下为图形属性
		String chart_title = mapTemp.get("chart_title").toString(); // 标题
		String title_enabled = mapTemp.get("title_enabled").toString(); // 标题是否可用
		String axis_title_enabled = mapTemp.get("axis_title_enabled") // x轴标题是否可用
				.toString();
		String title_font_size = mapTemp.get("title_font_size").toString(); // 标题显示字体大小
		String axis_title_font_size = mapTemp.get("axis_title_font_size") // x轴标题显示字体大小
				.toString();
		String animation = mapTemp.get("animation").toString(); // 是否显示动画
		String legend_enabled = mapTemp.get("legend_enabled").toString(); // 图例是否可用
		String legend_position = mapTemp.get("legend_position").toString(); // 图例显示位置
		String legend_align = mapTemp.get("legend_align").toString(); // 图例显示方式
		String y_axis_title = mapTemp.get("y_axis_title").toString(); // y轴标题

		model.addAttribute("title_enabled", title_enabled);
		model.addAttribute("axis_title_enabled", axis_title_enabled);
		model.addAttribute("title_font_size", title_font_size);
		model.addAttribute("axis_title_font_size", axis_title_font_size);
		model.addAttribute("animation", animation);
		model.addAttribute("legend_enabled", legend_enabled);
		model.addAttribute("legend_position", legend_position);
		model.addAttribute("legend_align", legend_align);
		model.addAttribute("chartType", chartType);
		model.addAttribute("dataTemp", data.toString());
		model.addAttribute("title", chart_title);
		model.addAttribute("xTitle", xAsixValue);
		model.addAttribute("yTitle", y_axis_title);
		model.addAttribute("maxCount", maxCount);
		model.addAttribute("minCount", minCount);
		model.addAttribute("num", df.format(num));
		model.addAttribute("legend_unit", legend_unit);

		return model;
	}

	/**
	 * 获取油量表数据data
	 * 
	 * @param tempSql
	 * @param yFiledNameList
	 * @param tcDataList
	 * @return
	 */
	public StringBuilder getCircleGauge(String tempSql,
			List<String> yFiledNameList, List<TnChartDataitems> tcDataList) {
		StringBuilder data = new StringBuilder();
		Map<String, Map<String, String>> map = chartSqlDao.getSeriesData2(
				tempSql, yFiledNameList);

		XmlUtils xmlUtils = new XmlUtils();
		ColorUtils colorUtils = new ColorUtils();
		TnColumnInfo tnInfo = new TnColumnInfo();
		String lengend = "";
		int size = 4;
		String color = "";
		String decimalDigits = "";
		String dataUnit = "";
		String tableId = "";
		List<TnTableInfo> tableInfos = null;
		for (int i = 0; i < tcDataList.size(); i++) {
			lengend = tcDataList.get(i).getyFieldCd();
			tableInfos = tableInfoService.getTableByName(tcDataList.get(i).getyFieldTableName());
			tableId = tableInfos.get(0).getTableId();
			decimalDigits = tcDataList.get(i).getExt2();
			tnInfo = tInfoService.getTNColumnInfoByName(tableId, lengend);
			dataUnit = tcDataList.get(i).getDataUnit();
			color = colorUtils.getRandColorCode();
			
			if (StringUtils.isEmpty(dataUnit)) {
				dataUnit = "";
			} else {
				dataUnit = "(" + dataUnit + ")";
			}
			if (StringUtils.isEmpty(decimalDigits)) {
				decimalDigits = String.valueOf(2);
			}
			
			data.append(xmlUtils.createXML2(map.get(lengend),
					tnInfo.getcName(), size, color, decimalDigits, dataUnit));
			size += 5;
		}

		return data;
	}

	/**
	 * 获取除油量表外的xml数据
	 * 
	 * @param tempSql
	 * @param yFiledNameList
	 * @param chartType
	 * @param tcDataList
	 * @return
	 */
	public StringBuilder getFourTypeData(String tempSql,
			List<String> yFiledNameList, String chartType,
			List<TnChartDataitems> tcDataList) {

		StringBuilder data = new StringBuilder();
		Map<String, List<AnychartDataBean>> map = chartSqlDao.getSeriesData(
				tempSql, yFiledNameList);

		String lengend = "";
		String SeriesName = "";
		String[] types = chartType.split(",");
		String type = chartType;
		int length = types.length;
		String decimalDigits = "";
		String dataUnit = "";
		
		XmlUtils xmlUtils = new XmlUtils();
		for (int i = 0; i < tcDataList.size(); i++) {
			lengend = tcDataList.get(i).getyFieldCd();// 来源数据库TnChartDataitems表Y_FIELD_NAME
			decimalDigits = tcDataList.get(i).getExt2();
			dataUnit = tcDataList.get(i).getDataUnit();
			SeriesName = tcDataList.get(i).getSeriesName();

			if (StringUtils.isEmpty(dataUnit)) {
				dataUnit = "";
			} else {
				dataUnit = "(" + dataUnit + ")";
			}
			if (StringUtils.isEmpty(decimalDigits)) {
				decimalDigits = String.valueOf(2);
			}
			if (length > 1) {
				if (i == 0) {
					type = "bar";
				} else {
					type = "line";
				}
			}
			
			data.append(xmlUtils.createXML(map.get(lengend), type, SeriesName, decimalDigits, dataUnit));
		}
		return data;
	}

	/**
	 * 去掉页面传来的数据 携带的 {}
	 * 
	 * @param param
	 * @return
	 */
	public String getDealParams(String param) {
		if (param.contains("{")) {
			param = param.replace("{", "");
		}
		if (param.contains("}")) {
			param = param.replace("}", "");
		}

		return param;
	}

	/**
	 * 解析字符串，获取携带的参数名称
	 * 
	 * @param param
	 * @return
	 */
	public String getPageParamName(String param) {
		String str = "";
		int index = param.indexOf("=");
		str = param.substring(0, index);
		return str;
	}

	/**
	 * 解析字符串，获取携带的参数值
	 * 
	 * @param param
	 * @return
	 */
	public String getPageParamValue(String param) {
		String str = "";
		int index = param.indexOf("=");
		str = param.substring(index + 1, param.length());
		return str;
	}

	public String getChartinfo(String chartId) {
		return null;
	}

	@SuppressWarnings("unchecked")
	public String getChartDetail(String field, String id) {
		List<TnChartDataitems> tcds = new ArrayList<TnChartDataitems>();
		List<TnChartParams> tcps = new ArrayList<TnChartParams>();
		List<TnTableColumnRelation>  tcrs = new ArrayList<TnTableColumnRelation>();
		CYDetailBean cydb = new CYDetailBean();
		tcds = (List<TnChartDataitems>) vecDao.getChartDetail(
				TnChartDataitems.class, id);
		tcps = (List<TnChartParams>) vecDao.getChartDetail(TnChartParams.class,
				id);
		tcrs = (List<TnTableColumnRelation>) vecDao.getChartDetail(TnTableColumnRelation.class,
				id);
		YQueryBean sd = dataitems2Y(tcds);
		cydb.setyQueryBean(sd);
		CQueryBean sp = params2CY(tcps);
		cydb.setcQueryBean(sp);
		MTRelationsBean mr = mrRelationsMTR(tcrs);
	    cydb.setMtRelationsBean(mr);
		cydb.setSuccess(true);
		return binder.toJson(cydb);
	}

	/**
	 * 保存图表数据配置表
	 */
	public YQueryBean dataitems2Y(List<TnChartDataitems> tcd) {
		int s = tcd.size();
		if (s < 1) {
			return null;
		}
		// y轴数据
		YQueryBean yField = new YQueryBean();
		YFieldsBean[] yb = new YFieldsBean[s];
		for (int i = 0; i < tcd.size(); i++) {
			TnChartDataitems t = tcd.get(i);
			YFieldsBean yBean = new YFieldsBean();
			yBean.setName(t.getSeriesId());
			yBean.setSeriesName(t.getSeriesName());
			/*
			 * t.getSeriesType(chartType); t.getDataUnit(null);
			 */
			yBean.setName(t.getyFieldCd());
			yBean.setSeriesName(t.getyFieldName());
			yBean.setTableName(t.getyFieldTableName());
			yBean.setFun(t.getyValueOpType());
			yBean.setCustomStle(t.getExt1());
			yBean.setDataUnit(t.getDataUnit());
			yBean.setDecimalPrecision(t.getExt2());
			yBean.setColumnId(t.getColumnId());
			yBean.setId(t.getColumnId());
			yb[i] = yBean;
		}
		yField.setFullSelect(yb);
		return yField;
	}

	/**
	 * 获取多表关联数据
	 * @param tcrs
	 * @return
	 */
	public MTRelationsBean mrRelationsMTR(List<TnTableColumnRelation> tcrs) {
		int ts = tcrs.size();
		if (ts < 1) {
			return null;
		}
		// 多表关联数据
		MTRelationsBean mrBean = new MTRelationsBean();
		MultiTableRelationBean[] cb = new MultiTableRelationBean[ts];
		TnColumnInfo tnInfo = new TnColumnInfo();
		for (int j = 0; j < ts; j++) {
			TnTableColumnRelation tcr = tcrs.get(j);
			MultiTableRelationBean mtrBean = new MultiTableRelationBean();
			mtrBean.setMainColumnId(tcr.getMainColumnId());
			mtrBean.setMainTableId(tcr.getMainTableId());
			mtrBean.setRelaTableId(tcr.getRelaTableId());
			mtrBean.setRelaColumnId(tcr.getRelaColumnId());
			tnInfo = tInfoService.getTNColumnInfoByName(tcr.getMainTableId(), tcr.getMainColumnId());
			mtrBean.setCnMaincolumnId(tnInfo.getcName());
			tnInfo = tInfoService.getTNColumnInfoByName(tcr.getRelaTableId(), tcr.getRelaColumnId());
			mtrBean.setCnRelacolumnId(tnInfo.getcName());
			cb[j] = mtrBean;
		}
		mrBean.setMtRelations(cb);
		return mrBean;
	}
	
	/**
	 * 取筛选条件，参数表
	 */
	public CQueryBean params2CY(List<TnChartParams> tcp) {
		int ts = tcp.size();
		if (ts < 1) {
			return null;
		}
		// 报表筛选数据
		CQueryBean cField = new CQueryBean();
		CFieldsBean[] cb = new CFieldsBean[ts];
		for (int j = 0; j < ts; j++) {
			TnChartParams tParams = tcp.get(j);
			CFieldsBean cBean = new CFieldsBean();
			// 图表参数表信息存储
			tParams.getParamsId();
			cBean.setName(tParams.getParamCd());
			cBean.setColumnId(tParams.getParamName());
			cBean.setDefaultValue(tParams.getDefaultValue());
			cBean.setOperator(tParams.getOpType());
			cBean.setParamType(tParams.getParamType());
			// 暂定为值操作类型
			// tParams.setOrderNum(orderNum); //多个参数时应有顺序
			cb[j] = cBean;
		}
		cField.setCONDITION(cb);
		return cField;
	}


	/**
	 * 根据轴相关数据，获取油量表中最大，最小字段值
	 * 
	 * @param columnStr
	 * @param eds
	 * @return
	 */
	public String getOilGaugeBeanInfoOfSql2(String columnStr, String eds, 
				String tables, List<TnTableColumnRelation> tnList) {
		String sql = "";
		if(StringUtils.isEmpty(tables)) {
			sql = "SELECT greatest(" + columnStr + ") as maxCount, least(" + columnStr
					+ ") as minCount from " + eds + " " + getAsNameByName(eds);
		} else {
			String[] tablesCon = tables.split(",");
			String fromTable = tablesCon[0];
			String joinTable = tablesCon[1];
			
			// 关联关系
			String relation = "";
			if (!StringUtils.isEmpty(tables)) {
				relation = addPoind2(tnList);
			}
			sql = "SELECT greatest(" + columnStr + ") as maxCount, least(" + columnStr
					+ ") as minCount from " + fromTable + " " + getAsNameByName(fromTable);
			if (!"".equals(joinTable)) {
				sql += " join " + joinTable + " " + getAsNameByName(joinTable) + " on " + relation;
			}
			
		}
		
		return sql;
	}

	/**
	 * 如果设置了关联关系，判断是关联哪张表的哪个字段
	 * 
	 * @param tableAlias
	 * @param relaField
	 * @param mulRelationData
	 * @return sql
	 */
	private String addPoind2(List<TnTableColumnRelation> tnList) {
		String sql = "";
		if (!StringUtils.isEmpty(tnList)) {
			StringBuffer buff = new StringBuffer();
			try {
				for (int i = 0; i < tnList.size(); i++) {
					buff.append(getAsNameById(tnList.get(i).getMainTableId()));
					buff.append(".");
					String leftColumn = tnList.get(i).getMainColumnId();
					buff.append(leftColumn + " = ");
					buff.append(getAsNameById(tnList.get(i).getRelaTableId()));
					String rightColumn = tnList.get(i).getRelaColumnId();
					buff.append(".");
					buff.append(rightColumn + " and ");
				} 
				sql = buff.toString();
				sql = sql.substring(0, sql.length()-5);
				System.out.println("关联关系：" + sql);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return sql;
	}
	
	
	/**
	 * 根据table_id查询别名
	 */
	public String getAsNameById(String id) {
		return chartSqlDao.getTableById(id).getAsName();
	}
	
	/**
	 * 根据id获取图表存储信息，然后进行sql的拼接。
	 */
	public String pieceSql(String id, String mulRelationData) {
		TnChartBaseinfo tnChartBaseinfo = vecDao.getChartInfo(id);
		List<TnChartDataitems> tnChartDataitemsList = vecDao.getChartDatas(id);
		List<TnChartParams> tnChartParamsList = vecDao.getChartParams(id);
		String pieceSqlString = getPieceSql(tnChartBaseinfo,
				tnChartDataitemsList, tnChartParamsList, mulRelationData);
		return pieceSqlString;
	}

	/**
	 * 通过数据库中保存的三张表信息获取拼接sql需要的信息
	 * 
	 * @param tnChartBaseinfo
	 * @param tnChartDataitemsList
	 * @param tnChartParamsList
	 * @return
	 */
	public String getPieceSql(TnChartBaseinfo tnChartBaseinfo,
			List<TnChartDataitems> tnChartDataitemsList,
			List<TnChartParams> tnChartParamsList,
			String mulRelationData) {

		// select X字段，FUN(Y字段) from 相关EDS数据表 join 相关REF维度表 on 关联字段 where 筛选条件
		// GOURPY BY X字段 ORDER BY 排序字段
		XFieldsBean xFields = getXField(tnChartBaseinfo);// X字段
		YFieldsBean[] yFields = getYField(tnChartDataitemsList);// Y字段
		CFieldsBean[] cfieldsArray = getConditions(tnChartParamsList);
		String sql = chartSqlPieceService.getPieceSql(cfieldsArray, xFields, yFields, mulRelationData);
		return sql;
	}
	private XFieldsBean getXField(TnChartBaseinfo baseInfo){
		XFieldsBean xField=new XFieldsBean();
		xField.setColType("1");
		//baseInfo.setDataUnit(null);
		xField.setcName(baseInfo.getxFieldName());
		xField.setTableName(baseInfo.getxFieldTableName());
		xField.setName(baseInfo.getxFieldCd());
		xField.setId(baseInfo.getxFieldCd());
		xField.setColumnId(baseInfo.getColumnId());
		xField.setText(baseInfo.getDrillPath()); // 设置 DrillPath
		return xField;
	}
private YFieldsBean[] getYField(List<TnChartDataitems> tnChartDataitemsList){
	int arrSize=tnChartDataitemsList.size();
	YFieldsBean[] yFieldsBeanArr=new YFieldsBean[arrSize];
	for(int i=0;i<arrSize;i++){
		TnChartDataitems tDataitems=tnChartDataitemsList.get(i);
		YFieldsBean yBean=new YFieldsBean();
		//yBean.setName(tDataitems.getSeriesId());
		yBean.setSeriesName(tDataitems.getSeriesName());
		yBean.setDataUnit(tDataitems.getDataUnit());
		yBean.setName(tDataitems.getyFieldCd());
		//yBean.setSeriesName(tDataitems.getyFieldName());
		yBean.setTableName(tDataitems.getyFieldTableName());
		yBean.setFun(tDataitems.getyValueOpType());
		yBean.setCustomStle(tDataitems.getExt1());
		yBean.setDecimalPrecision(tDataitems.getExt2());
		yFieldsBeanArr[i]=yBean;
	}
	return yFieldsBeanArr;
}

	private CFieldsBean[] getConditions(List<TnChartParams> tnChartParamsList) {
		int listSize = tnChartParamsList.size();
		CFieldsBean[] cFieldsBeanArray = new CFieldsBean[listSize];
		for (int i = 0; i < listSize; i++) {
			TnChartParams tnChartParams = tnChartParamsList.get(i);
			CFieldsBean cBean = new CFieldsBean();
			cBean.setName(tnChartParams.getParamCd());
			cBean.setParamName(tnChartParams.getParamName());
			cBean.setParamType(tnChartParams.getParamType());
			cBean.setDefaultValue(tnChartParams.getDefaultValue());
			cBean.setColType(tnChartParams.getDataType());
			cBean.setTableName(tnChartParams.getParamTextvalueFromTableNam());
			cBean.setOperator(tnChartParams.getOpType());
			cFieldsBeanArray[i] = cBean;
		}
		return cFieldsBeanArray;
	}



	private String getUrl(String chartType) {
		String goPage = "";
		if (chartType.equalsIgnoreCase("bar")) {
			goPage = "/anychartTemplates/bar";
		} else if ("bar,Line".equalsIgnoreCase(chartType)) {
			goPage = "/anychartTemplates/barLine";
		} else if ("pie".equalsIgnoreCase(chartType)) {
			goPage = "/anychartTemplates/pie";
		} else if ("spline".equalsIgnoreCase(chartType)) {
			goPage = "/anychartTemplates/line";
		} else if ("circularGauge".equalsIgnoreCase(chartType)) {
			goPage = "/anychartTemplates/oilGauge";
		}

		return goPage;
	}

	private String createSql(String params, TnChartBaseinfo tChartInfo,
			List<TnChartParams> tcParamsList) {
		String chartType = tChartInfo.getChartType(); // 图表类型
		String chartDataSql = tChartInfo.getChartDataSql();
		String tempSql = null;
		String strParams = null;
		if (StringUtils.isEmpty(params)) {
			strParams = params;
		} else {
			strParams = this.getDealParams(params);
		}
		if (StringUtils.isEmpty(strParams)) {
			tempSql = chartDataSql;
		} else {
			StringBuffer paramSql = new StringBuffer();
			String[] strParmas = strParams.split(",");
			int k = 0;
			TnChartParams tChartParams = null;
			for (int i = 0; i < strParmas.length; i++) {
				for (int j = 0; j < tcParamsList.size(); j++) {
					tChartParams = tcParamsList.get(j);
					if (this.getPageParamName(strParmas[i]).equals(
							tChartParams.getParamCd())) {
						if (k > 0) {
							paramSql.append(" and ");
						}
						paramSql.append(this.getPageParamName(strParmas[i]))
								.append(" " + tChartParams.getOpType() + " ")
								.append("\'")
								.append(this.getPageParamValue(strParmas[i]))
								.append("\'");
						k++;
					}
				}
			}
			if ("circularGauge".equals(chartType)) {
				tempSql = chartDataSql + " and " + paramSql.toString();
			} else {
				tempSql = chartDataSql.replace("GROUP",
						" where " + paramSql.toString() + "  GROUP");
			}

			log.info("sql: {}", tempSql);
		}
		return tempSql;
	}
	
	/**
	 * 根据表名查询别名
	 */
	public String getAsNameByName(String name) {
		return chartSqlDao.getAsNameByName(name);
	}
}
